package offline

import (
	"encoding/hex"
	"fmt"

	"github.com/filecoin-project/lotus/cli/offline/local"
	"github.com/urfave/cli/v2"
)

var WalletSign = &cli.Command{
	Name:      "sign",
	Usage:     "sign a message",
	ArgsUsage: "<signing address> <hexMessage>",
	Flags:     commonFlag,
	Action: func(cctx *cli.Context) error {

		if !cctx.Args().Present() || cctx.NArg() != 2 {
			return fmt.Errorf("must specify signing address and message to sign")
		}
		msg, err := hex.DecodeString(cctx.Args().Get(1))
		if err != nil {
			return err
		}

		keyInfo, err := local.SignKeyInfo(cctx, cctx.String("local-private-key"))
		if err != nil {
			return err
		}
		sig, err := local.WalletSign(keyInfo.Type, keyInfo.PrivateKey, msg)

		if err != nil {
			return err
		}

		sigBytes := append([]byte{byte(sig.Type)}, sig.Data...)

		fmt.Println(hex.EncodeToString(sigBytes))
		return nil
	},
}
